/**
 * 
 */
package com.surelution.cppei.weixin.gate

import static com.surelution.whistle.core.Attribute.*

import com.surelution.whistle.core.Configure
import com.surelution.whistle.core.NewsAttribute


/**
 * @author <a href="mailto:guangzong.syu@gmail.com">guangzong</a>
 *
 */
class SubscribingAction extends CppeiBaseAction {

	/* (non-Javadoc)
	 * @see com.surelution.whistle.core.BaseAction#accept()
	 */
	@Override
	public boolean accept() {
		getParam(KEY_MsgType) == "event" && getParam("Event") == "subscribe"
	}

	/* (non-Javadoc)
	 * @see com.surelution.whistle.core.BaseAction#execute()
	 */
	@Override
	public void execute() {
		def eventKey = getParam("EventKey")
		if(eventKey) {
			if(eventKey.startsWith("qrscene_")) {
				def qrscene = eventKey.substring("qrscene_".length())
				if(qrscene) {
					def code = qrscene as Integer
					def subAccount = QrAssign.findByQrscene(code)
					if(subAccount) {
						def ssa = SubscriberSubAccount.findAllBySubAccountAndSubscriber(subAccount, subscriber)
						if(!ssa) {
							ssa = new SubscriberSubAccount(subAccount:subAccount, subscriber:subscriber, userid:UUID.randomUUID().toString())
							ssa.save(flush:true)
							subscriber.account = ssa
							subscriber.save(flush:true)
						}
					}
				}
			}
		}
		
		def account = subscriber.account
		if(!account) {
			def url = "http://${rootPath}/branch/"
			Configure c = Configure.config()
			def s = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=${c.appid}&response_type=code&scope=snsapi_base&state=STATE&redirect_uri=${URLEncoder.encode(url, "utf8")}#wechat_redirect"
			
			def na = new NewsAttribute()
			na.add("欢迎关注", "为了更好的为您服务，您可以根据您目前所在地，选择一个分公司", "http://${rootPath}/app-images/welcome.jpg", s)
			put(na)
		} else {
			delegateToSubAccount()
		}
	}

}
